package com.google.screen;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.client.android.CaptureActivity;
import com.google.zxing.client.android.R;

public class Result extends Activity {

	private Bundle mBun;
	private TextView mTxtTitle;
	private TextView mTxtBarcode;
	private TextView mTxtStatus;
	private TextView mTxtDescription;
	private TextView mTxtStartdate;
	private TextView mTxtEnddate;
	private String mStrToken;
	private SharedPreferences mSharedPref;
	private RelativeLayout mRlayMenu;
	private ImageView mImgMenu;
	private boolean mBlnMenu = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.popupinformation);

		mBun = getIntent().getExtras();
		initialContentView();

		mStrToken = getIntent().getExtras().getString("Token");
		mSharedPref = getSharedPreferences("BarcodePref", Context.MODE_PRIVATE);

		mRlayMenu = (RelativeLayout) findViewById(R.id.rlayResultMenu);
		mImgMenu = (ImageView) findViewById(R.id.imgResultLogo);

		mImgMenu.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mBlnMenu) {
					mRlayMenu.removeAllViews();
					mRlayMenu.setVisibility(View.GONE);
					mBlnMenu = false;
				} else {
					LayoutInflater inf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					View view = inf.inflate(R.layout.menu, null);
					mRlayMenu.addView(view);
					mRlayMenu.setVisibility(View.VISIBLE);
					mBlnMenu = true;
				}
			}
		});
	}

	private void initialContentView() {
		mTxtTitle = (TextView) findViewById(R.id.txtPopUpTitle);
		mTxtBarcode = (TextView) findViewById(R.id.txtPopUpCode);
		mTxtStatus = (TextView) findViewById(R.id.txtPopUpStatus);
		mTxtDescription = (TextView) findViewById(R.id.txtPopUpDescription);
		mTxtStartdate = (TextView) findViewById(R.id.txtPopUpStartDate);
		mTxtEnddate = (TextView) findViewById(R.id.txtPopUpEndDate);
		Button btnHome = (Button) findViewById(R.id.btnPopUpHome);

		mTxtBarcode.setText("Barcode: " + mBun.getString("barcode"));
		if (mBun.get("code") == null) {
			mTxtStatus.setVisibility(View.GONE);
			btnHome.setVisibility(View.GONE);
			showInformations();
		} else {
			if (mBun.getInt("code") == 1 || mBun.getInt("code") == -3) {
				showInformations();
			} else {
				mTxtTitle.setVisibility(View.GONE);
				mTxtDescription.setVisibility(View.GONE);
				mTxtStartdate.setVisibility(View.GONE);
				mTxtEnddate.setVisibility(View.GONE);
			}
			mTxtStatus.setText("Status: " + mBun.getInt("code") + " - "
					+ mBun.getString("message"));
		}
	}

	private void showInformations() {
		mTxtTitle.setText("Title: " + mBun.getString("title"));
		mTxtDescription.setText("Content: " + mBun.getString("description"));
		mTxtStartdate.setText("Start date: " + mBun.getString("start_date"));
		mTxtEnddate.setText("End date: " + mBun.getString("end_date"));
		ImageView image = (ImageView) findViewById(R.id.imgPopUp);
		new DownloadImageTask(image).execute("http://www.chimrawa.com/uploads/"
				+ mBun.getString("image"));
	}

	public void backtoHome(View v) {
		Intent intent = new Intent(Result.this, Control.class);
		intent.putExtra("Token", mBun.getString("Token"));
		startActivity(intent);
		finish();
	}

	private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
		ImageView bmImage;

		public DownloadImageTask(ImageView bmImage) {
			this.bmImage = bmImage;
		}

		protected Bitmap doInBackground(String... urls) {
			String urldisplay = urls[0];
			Bitmap mIcon11 = null;
			try {
				InputStream in = new java.net.URL(urldisplay).openStream();
				mIcon11 = BitmapFactory.decodeStream(in);
			} catch (Exception e) {
				Log.e("Error", e.getMessage());
				e.printStackTrace();
			}
			return mIcon11;
		}

		protected void onPostExecute(Bitmap result) {
			bmImage.setImageBitmap(result);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		return true;
	}

	@Override
	public void onBackPressed() {
		if (mBun.get("code") == null) {
			super.onBackPressed();
		} else {
			Intent intent = new Intent(Result.this, CaptureActivity.class);
			intent.putExtra("Token", mBun.getString("Token"));
			startActivity(intent);
			finish();
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (mRlayMenu.isShown()) {
			mRlayMenu.removeAllViews();
			mRlayMenu.setVisibility(View.GONE);
			mBlnMenu = false;
		}
		return super.onTouchEvent(event);
	}

	public void startScan(View v) {
		Intent intent = new Intent(Result.this, CaptureActivity.class);
		intent.putExtra("Token", mStrToken);
		startActivity(intent);
		finish();
	}

	public void contact(View v) {
		Intent intent = new Intent(Result.this, Contact.class);
		intent.putExtra("Token", mStrToken);
		startActivity(intent);
		finish();
	}

	public void logout(View v) {
		new Logout(this, mStrToken).execute();
	}

	public void parametres(View v) {
		mRlayMenu.removeAllViews();
		mRlayMenu.setVisibility(View.GONE);
	}

	public void viewFAQs(View v) {
		Intent intent = new Intent(Result.this, FAQs.class);
		intent.putExtra("Token", mStrToken);
		startActivity(intent);
		finish();
	}

	public void viewControlHistory(View v) {
		Intent intent = new Intent(Result.this, History.class);
		intent.putExtra("Token", mStrToken);
		startActivity(intent);
		finish();
	}

	public void setStringPref(SharedPreferences sharedPref, String name,
			String value) {
		SharedPreferences.Editor editor = sharedPref.edit();
		editor.putString(name, value);
		editor.commit();
	}

	public class Logout extends AsyncTask<String, Integer, String> {

		private Context mCtx;
		private ProgressDialog mProDialog;
		private String mStrToken;
		private Intent intent;

		public Logout(Context ctx, String strToken) {
			mCtx = ctx;
			mProDialog = new ProgressDialog(mCtx);
			mStrToken = strToken;
			intent = new Intent(mCtx, Login.class);
		}

		@Override
		protected String doInBackground(String... params) {
			setStringPref(mSharedPref, "token", "");
			StringBuffer uri = new StringBuffer(
					"http://www.chimrawa.com/service.php/authentication/logout?");
			uri.append("token=" + URLEncoder.encode(mStrToken));
			Log.i("uri", uri.toString());
			String param[] = new String[2];
			param[0] = uri.toString();
			param[1] = "logout";

			Authentication authentication = new Authentication(mCtx);
			authentication.execute(param);
			try {
				ContentValues data = authentication.get();
				if (data != null) {
					if (data.getAsInteger("code") == 1
							&& data.getAsString("statusheader").equals("ok")) {
						return "logout";
					} else {
						return "disconnect";
					}
				} else {
					return "notconnect";
				}
			} catch (InterruptedException e) {
				Log.i("InterruptedException", e.getMessage());
			} catch (ExecutionException e) {
				Log.i("ExecutionException", e.getMessage());
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			mProDialog.dismiss();
			if (result.equals("logout")) {
				startActivity(intent);
				finish();
			}
			if (result.equals("disconnect")) {
				Toast.makeText(mCtx, "Can't disconnect!", Toast.LENGTH_SHORT)
						.show();
			}
			if (result.equals("notconnect")) {
				Toast.makeText(mCtx, "Can't connect to server!",
						Toast.LENGTH_SHORT).show();
			}
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			mProDialog.setTitle("Logout Account");
			mProDialog.setMessage("Connecting...");
			mProDialog.setCancelable(false);
			mProDialog.setCanceledOnTouchOutside(false);
			mProDialog.show();
			super.onPreExecute();
		}

	}

}
